package com.chengduservice.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.MutablePropertySources;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * create by yongli on 2022-05-29 11:28
 * 对于环境变量的读取
 */
@Configuration
public class RefreshConfig {

    @Autowired
    private ConfigurableEnvironment environment;

    @PostConstruct
    public void setUp() {
        test();
        Map<String, Object> system = this.environment.getSystemEnvironment();
        system.forEach((k, v) -> {
            System.out.print(k + ":");
            System.out.println(v);
        });
        // 要对这些类有一定的认识才行
        MutablePropertySources sources = this.environment.getPropertySources();
        sources.forEach((c) -> {
            System.out.println(c);
            System.out.println(c.getName());
            System.out.println(c.getSource());
        });
        // 看看hashMap值是否能读到
        System.out.println("能否读到这个值:" + this.environment.getProperty("user.name"));

    }

    public void test() {
        HashMap<String, Object> tests = new HashMap<>();
        tests.put("user.name", "liyong");
        tests.put("user.age", "12");
        MapPropertySource mapPropertySource = new MapPropertySource("test", tests);
        this.environment.getPropertySources().addLast(mapPropertySource);

    }
}
